﻿using System.Text;

using RabbitMQ.Client;

namespace Tszy.Unlimited.Base.Infrastructure.Queues.RabbitMQ;

/// <summary>
/// RabbitMQ 消息发布者。
/// </summary>
public interface IRabbitMQPublisher
{
    /// <summary>
    /// 向指定的路由 KEY 发送消息。
    /// </summary>
    /// <param name="routeKey">路由 KEY。</param>
    /// <param name="data">发送内容。</param>
    void Send(string routeKey, string data);
}

/// <summary>
/// RabbitMQ 消息发布者。
/// </summary>
public class RabbitMQPublisher : IRabbitMQPublisher
{
    private readonly RabbitMQConfig _config;

    private readonly IModel _channel;

    /// <summary>
    /// 初始化。
    /// </summary>
    /// <param name="config">RabbitMQ 配置。</param>
    /// <param name="channel"></param>
    public RabbitMQPublisher(RabbitMQConfig config, IModel channel)
    {
        _config = config;
        _channel = channel;
    }

    /// <summary>
    /// 向指定的路由 KEY 发送消息。
    /// </summary>
    /// <param name="routeKey">路由 KEY。</param>
    /// <param name="data">发送内容。</param>
    public void Send(string routeKey, string data)
    {
        var body = Encoding.UTF8.GetBytes(data);

        _channel.BasicPublish(_config.ExchangeName, routeKey, null, body);
    }
}